package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.AutoSupplierManager;
import com.fish.anne.model.AutoSupplier;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class AutoSupplierAction extends BaseAction implements Preparable {
    private AutoSupplierManager autoSupplierManager;
    private List autoSuppliers;
    private AutoSupplier autoSupplier;
    private Long  spId;

    public void setAutoSupplierManager(AutoSupplierManager autoSupplierManager) {
        this.autoSupplierManager = autoSupplierManager;
    }

    public List getAutoSuppliers() {
        return autoSuppliers;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String autoSupplierId = getRequest().getParameter("autoSupplier.spId");
            if (autoSupplierId != null && !autoSupplierId.equals("")) {
                autoSupplier = autoSupplierManager.get(new Long(autoSupplierId));
            }
        }
    }

    public String list() {
        autoSuppliers = autoSupplierManager.getAll();
        return SUCCESS;
    }

    public void setSpId(Long  spId) {
        this. spId =  spId;
    }

    public AutoSupplier getAutoSupplier() {
        return autoSupplier;
    }

    public void setAutoSupplier(AutoSupplier autoSupplier) {
        this.autoSupplier = autoSupplier;
    }

    public String delete() {
        autoSupplierManager.remove(autoSupplier.getSpId());
        saveMessage(getText("autoSupplier.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (spId != null) {
            autoSupplier = autoSupplierManager.get(spId);
        } else {
            autoSupplier = new AutoSupplier();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (autoSupplier.getSpId() == null);

        autoSupplierManager.save(autoSupplier);

        String key = (isNew) ? "autoSupplier.added" : "autoSupplier.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}